package me.ianhe.wedding.handler;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.ianhe.wedding.dao.SystemUserMapper;
import me.ianhe.wedding.dao.WeddingMapper;
import me.ianhe.wedding.entity.SystemUser;
import me.ianhe.wedding.entity.Wedding;
import me.ianhe.wedding.enums.UserStatusEnum;
import me.ianhe.wedding.enums.UserTypeEnum;
import me.ianhe.wedding.pojo.WeddingMsg;
import me.ianhe.wedding.socket.WeddingSocketEndPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

import static me.chanjar.weixin.common.api.WxConsts.XmlMsgType;

/**
 * @author iHelin
 * @date 2019/8/26 21:04
 */
@Component
public class MsgHandler extends AbstractHandler {

    @Autowired
    private WeddingSocketEndPoint weddingSocketEndPoint;

    @Autowired
    private SystemUserMapper systemUserMapper;

    @Autowired
    private WeddingMapper weddingMapper;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context,
                                    WxMpService weixinService,
                                    WxSessionManager sessionManager) throws WxErrorException {

        if (!XmlMsgType.EVENT.equals(wxMessage.getMsgType())) {
            logger.warn("非事件消息：{}", wxMessage);
        }

        String resContent;

        SystemUser wechatUser = systemUserMapper.selectByOpenId(wxMessage.getFromUser());

        if (wechatUser == null) {
            WxMpUser userWxInfo = weixinService.getUserService().userInfo(wxMessage.getFromUser());

            SystemUser systemUser = new SystemUser();
            systemUser.setType(UserTypeEnum.WECHAT_USER.value());
            systemUser.setUserStatue(UserStatusEnum.DEFAULT_USER.value());

            systemUser.setNickname(userWxInfo.getNickname());
            systemUser.setOpenid(userWxInfo.getOpenId());
            systemUser.setCity(userWxInfo.getCity());
            systemUser.setCountry(userWxInfo.getCountry());
            systemUser.setProvince(userWxInfo.getProvince());
            systemUser.setLanguage(userWxInfo.getLanguage());
            systemUser.setQrScene(userWxInfo.getQrScene());
            systemUser.setQrSceneStr(userWxInfo.getQrSceneStr());
            systemUser.setRemark(userWxInfo.getRemark());
            systemUser.setGroupId(userWxInfo.getGroupId());
            systemUser.setHeadImgUrl(userWxInfo.getHeadImgUrl());
            systemUser.setSex(userWxInfo.getSex());
            systemUser.setSexDesc(userWxInfo.getSexDesc());
            systemUser.setSubscribe(userWxInfo.getSubscribe());
            systemUser.setSubscribeTime(userWxInfo.getSubscribeTime());
            systemUser.setSubscribeScene(userWxInfo.getSubscribeScene());
            systemUserMapper.insert(systemUser);
            resContent = "加入成功";

        } else {
            if (UserStatusEnum.DEFAULT_USER.value().equals(wechatUser.getUserStatue())) {

                Wedding wedding = weddingMapper.selectByCode(wxMessage.getContent());

                if (wedding != null) {
                    //更新微信状态
                    wechatUser.setUserStatue(UserStatusEnum.BINDING_USER.value());
                    systemUserMapper.updateByPrimaryKeySelective(wechatUser);

                    systemUserMapper.insertUserWedding(wechatUser.getId(), wedding.getId());

                    resContent = "绑定成功！\n欢迎参加" + wedding.getBridegroom() + "和" + wedding.getBride() + "的婚礼！💒" +
                            "\n一起来祝福他们吧！";
                } else {
                    resContent = "您发送的内容有误！";
                }
            } else if (UserStatusEnum.BINDING_USER.value().equals(wechatUser.getUserStatue())) {
                Integer weddingId = systemUserMapper.getWeddingIdByUserId(wechatUser.getId());
                WeddingMsg weddingMsg = new WeddingMsg();
                weddingMsg.setNickname(wechatUser.getNickname());
                weddingMsg.setHeadImgUrl(wechatUser.getHeadImgUrl());
                weddingMsg.setContent(wxMessage.getContent());
                weddingSocketEndPoint.sendMessagesChannel(weddingMsg, weddingId);

                resContent = "发送成功！";
            } else {
                resContent = "您发送的消息格式不正确！";
            }
        }



        return WxMpXmlOutMessage.TEXT()
                .content(resContent)
                .fromUser(wxMessage.getToUser())
                .toUser(wxMessage.getFromUser())
                .build();
    }

}
